<!--发布房源的多图上传组件-->
<template>
  <div>
    <!--多图上传-->
    <el-upload action="http://localhost:8089/myhome_war_exploded/UploadController/addImg.action?imgPath=images/manyhouse"
      list-type="picture-card" :on-preview="handlePictureCardPreview" :on-success="onSuccess" :on-remove="handleRemove">
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!--提交和上一步-->
    <el-button type="primary" @click="Step(2)">上一步</el-button>
    <el-button type="success" @click="Step(1)">提交</el-button>
  </div>
</template>
<script>
  export default {
    data() {
      return {
        //图片上传
        dialogImageUrl: '',
        dialogVisible: false,
        fileLength: 0, //图片长度 验证

        //数据
        datas: {
          imgs: [{ihouseid:'',imgsurl:''}], //测试
          upimgs:[{imgsurl:''}],//实际提交的
          num: 0 //上一步下一步
        }
      }
    },
    methods: {
      Step(num) {
        //先判断是否选择了图片
        if (this.fileLength <= 0 &&num===1) {
          this.$message.error("请选择图片");
          return;
        }
        //整理只保留图片路径
        for(var i=0;i<this.datas.imgs.length;i++){
          let img={imgsurl:this.datas.imgs[i].imgsurl};
          this.datas.upimgs[i]=img;
        }
        //1提交 2上一步
        this.datas.num = num;
        this.$emit('imgEvent', this.datas) // 把数据传给父组件
      },
      //成功回调
      onSuccess(response, file, fileList) {
        this.fileLength += 1 // 表示有一张图片
        console.log(response, file, fileList);
       // this.datas.imgs[file.uid] = response; //给指定位置保存路径
        let obj={ihouseid:file.uid,imgsurl:response};
        this.datas.imgs[fileList.length-1]=obj;
        console.log(this.datas.imgs);
      },
      //删除
      async handleRemove(file, fileList) {
        console.log(file, fileList);
        // console.log(this.datas.imgs[file.uid]);
        //后端删除
        this.fileLength -= 1 // 表示删了一张图片
        var removeurl='';
        for(var i=0;i<this.datas.imgs.length;i++){
          if(this.datas.imgs[i].ihouseid===file.uid){
            removeurl=this.datas.imgs[i].imgsurl;
            this.datas.imgs.splice(i,1);//删除
          }
        }
       console.log(this.datas.imgs);
        //去后端把服务器的指定图片删了
        var formdata2 = new FormData();
        formdata2.append("imgPath",removeurl);
        formdata2.append("filename", 'manyhouse');
        const {
          data: res
        } = await this.$axios.post(
          'UploadController/removeImg.action', formdata2)
        console.log(res);
      },
      //预览
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      }

    }
  }
</script>
<style scoped>
.el-button{
  margin-top:25px;
}

</style>
